package com.et114.components.mail;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;

import freemarker.template.Template;
import freemarker.template.TemplateException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

/**
 * @author guanhw
 * SIMPALE
 */
public abstract class MailService {
	protected static final Log logger = LogFactory.getLog( MailService.class );
	private FreeMarkerConfigurer mailTemplateEngine = null;
	public void setMailTemplateEngine( FreeMarkerConfigurer mailTemplateEngine ) {
		this.mailTemplateEngine = mailTemplateEngine;
	}


	public abstract void send( SimpleMailMessage msg ) throws Exception;


	public void send( String from , String to , String subject , String text ) throws Exception {
		SimpleMailMessage msg = new SimpleMailMessage();
		msg.setFrom( from );
		msg.setTo( to );
		msg.setSubject( subject );
		msg.setText( text );
		send( msg );
	}


	public abstract void send( SimpleMailMessage msg , String templateName , Map model ) throws Exception;


	public String generateEmailContent( String templateName, Map map ) throws Exception {
		try {
			Template t = mailTemplateEngine.getConfiguration().getTemplate( templateName );
			return FreeMarkerTemplateUtils.processTemplateIntoString( t , map );
		} catch ( TemplateException e ) {
		    logger.error( "Error while processing FreeMarker template " , e );
		} catch ( FileNotFoundException e ) {
		    logger.error( "Error while open template file " , e );
		} catch ( IOException e ) {
		    logger.error( "Error while generate Email Content " , e );
		}
		return null;
	}
}
